package com.white.ipcsocket;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;

public class MainActivity extends AppCompatActivity
{

    private LinearLayout container;
    private Button send;
    private EditText et;

    private Intent serverIntent;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViews();
        serverIntent = new Intent(this, ServerService.class);
        startService(serverIntent);
    }

    private void findViews()
    {
        container = (LinearLayout) findViewById(R.id.chat_layout);
        send = (Button) findViewById(R.id.send);
        send.setEnabled(false);
        et = (EditText) findViewById(R.id.content);
    }

    private Socket clientSocket;
    private PrintWriter writer;

    public void click(View view)
    {
        if(view.getId() == R.id.send)
        {
            CharSequence cs = et.getText();
            if(!TextUtils.isEmpty(cs))
            {
                String mmsg = cs.toString();
                if(writer != null)
                {
                    writer.print(mmsg);
                    et.setText("");
                }
            }
        }else if(view.getId() == R.id.open)
        {
            new Thread(new Client()).start();
        }
    }

    private class Client implements Runnable
    {
        @Override
        public void run()
        {
            Socket c = null;
            while (c == null)
            {
                try
                {
                    c = new Socket("localhost", 8798);
                    clientSocket = c;
                    writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream(), "utf-8")), true);
                    mHandler.sendEmptyMessage(0);
                } catch (IOException e)
                {
                    SystemClock.sleep(1200);
                    e.printStackTrace();
                }
            }
        }
    }

    private Handler mHandler = new Handler()
    {
        @Override
        public void handleMessage(Message msg)
        {
            switch (msg.what)
            {
                case 0:
                    Toast.makeText(MainActivity.this, "连接服务器成功", Toast.LENGTH_SHORT).show();
                    readFromServer();
                    send.setEnabled(true);
                    break;
                case 1:
                    TextView tv = new TextView(MainActivity.this);
                    tv.setText(msg.obj.toString());
                    container.addView(tv);
                    break;
            }
        }
    };

    private void readFromServer()
    {
        new Thread()
        {
            @Override
            public void run()
            {
                BufferedReader br = null;
                try
                {
                    br = new BufferedReader(new InputStreamReader(clientSocket.getInputStream(), "utf-8"));
                    while(!MainActivity.this.isFinishing())
                    {
                        String msg = br.readLine();
                        if(!TextUtils.isEmpty(msg))
                        {
                            mHandler.obtainMessage(1, msg).sendToTarget();
                        }
                    }
                } catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    @Override
    protected void onDestroy()
    {
        if(clientSocket != null)
        {
            try
            {
                clientSocket.shutdownInput();
                clientSocket.close();
            } catch (IOException e)
            {
                e.printStackTrace();
            }
        }
        if(serverIntent != null)
        {
            stopService(serverIntent);
        }
        super.onDestroy();
    }
}
